package com.golddaymicromall.activity.salemanager;

import android.app.AlertDialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.setting.personal.address.AddressChoiceActivity;
import com.golddaymicromall.adapter.ConfirmPayAdapter;
import com.golddaymicromall.adapter.GiftAdapter;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.ActiveInfo;
import com.golddaymicromall.bean.ActiveProInfo;
import com.golddaymicromall.bean.AddressInfo;
import com.golddaymicromall.bean.ProductInfo;
import com.golddaymicromall.util.MD5;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class ConfirmPayActivity extends BaseActivity implements ListView.OnClickListener {

    private List<ProductInfo> list;
    private List<AddressInfo> listAddress = new ArrayList<AddressInfo>();
    public static final int REQUSET = 1;
    private String addressid;
    int num;
    float PV; //PV
    float SaleAids; //辅销品价格
    float RealPay; //实付价
    float discount;
    private float allPrice;
    private String ids;
    private String count;
    private ConfirmPayAdapter adapter;
    String customerId;

    private TextView mAllPrice;
    private TextView mSecond_num;
    private ListView mLv;
    private LinearLayout mConfirmPayBack;
    private LinearLayout mConfirmPay_ChangeAddress;
    private TextView mUsername;
    private TextView mAddress;
    private TextView mPhone;
    private TextView mConfirmPayment;
    private TextView mDiscount;
    private TextView mConfirmAddCart;
    List<ActiveInfo> activeInfos = new ArrayList<ActiveInfo>();
    List<ActiveProInfo> activeProInfos = new ArrayList<ActiveProInfo>();

    List<ActiveProInfo> activeProInfosAdapter;

    GiftAdapter giftAdapter;
    ListView mGiftlv;
    TextView mGiftText;
    int activeFlag = 1;
    String mDeptFlag;
    //创建观察者
    private DataSetObserver sumObserver = new DataSetObserver() {
        /**
         * 当Adapter的notifyDataSetChanged方法执行时被调用
         */
        @Override
        public void onChanged() {
            super.onChanged();
            //执行相应的操作
            plusPrice();
        }

        /**
         * 当Adapter 调用 notifyDataSetInvalidate方法执行时被调用
         */
        @Override
        public void onInvalidated() {
            super.onInvalidated();
            //执行相应的操作
        }
    };

    //接收返回的值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConfirmPayActivity.REQUSET && resultCode == RESULT_OK) {
            addressid = data.getStringExtra("id");
            String nameAddress = data.getStringExtra("name_address");
            String address = data.getStringExtra("address");
            String phone = data.getStringExtra("phone");
            mUsername.setText("收货人：" + nameAddress);
            mPhone.setText(phone);
            mAddress.setText("地址：" + address);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_pay);
        customerId = SPUtils.get(getApplicationContext(), "Id", "").toString();
        mDeptFlag = SPUtils.get(getApplicationContext(), "deptFlag", "").toString();
        list = (List<ProductInfo>) getIntent().getSerializableExtra("listFlag");
        initView();
        plusPrice();
        attemptAddress();
    }

    private void initView() {
        mLv = (ListView) findViewById(R.id.secondpurchase_listview);
        mGiftlv = (ListView) findViewById(R.id.gift_listview);
        mAllPrice = (TextView) findViewById(R.id.allPrice);
        mSecond_num = (TextView) findViewById(R.id.second_num);
        mConfirmPayBack = (LinearLayout) findViewById(R.id.confirmpay_back);
        mConfirmPay_ChangeAddress = (LinearLayout) findViewById(R.id.confirmPay_changeAddress);
        mUsername = (TextView) findViewById(R.id.confirmPay_username);
        mAddress = (TextView) findViewById(R.id.confirmPay_address);
        mPhone = (TextView) findViewById(R.id.confirmPay_phone);
        mConfirmPayment = (TextView) findViewById(R.id.confirmpayment);
        mDiscount = (TextView) findViewById(R.id.confirmdiscount);
        mConfirmAddCart = (TextView) findViewById(R.id.confirmAddcart);
        mGiftText = (TextView) findViewById(R.id.gift_text);
        mAddress.setText("您还没有默认收货地址，请到个人设置中设置地址");
        mConfirmAddCart.setOnClickListener(this);
        mConfirmPayment.setOnClickListener(this);
        mConfirmPayBack.setOnClickListener(this);
        mConfirmPay_ChangeAddress.setOnClickListener(this);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCount() == 0) {
                list.remove(i);
            }
        }
        adapter = new ConfirmPayAdapter(list, ConfirmPayActivity.this);
        adapter.registerDataSetObserver(sumObserver);
        mLv.setAdapter(adapter);
        String secondAct = SPUtils.get(getApplicationContext(), "secondAct", "").toString();
        String secondActPro = SPUtils.get(getApplicationContext(), "secondActPro", "").toString();
        Log.e("secondAct", secondAct);
        Log.e("secondActPro", secondActPro);
        if (!"0".equals(secondAct)) {
            activeInfos = JSON.parseArray(secondAct, ActiveInfo.class);
        }
        if (!"0".equals(secondActPro)) {
            activeProInfos = JSON.parseArray(secondActPro, ActiveProInfo.class);
        }
    }

    //计算总金额
    public void plusPrice() {
        allPrice = 0f;
        num = 0;
        PV = 0f;
        SaleAids = 0f;
        RealPay = 0f;
        boolean flag = true;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        String shopGrade = SPUtils.get(getApplicationContext(), "shop_Grade", "").toString();
        switch (shopGrade) {
            case "1":
                discount = (float) 0.6;
                mDiscount.setText("6折");
                break;
            case "2":
                discount = (float) 0.5;
                mDiscount.setText("5折");
                break;
        }
        for (ProductInfo info : list) {
            if (info.flag) {
                if (!info.getPtid().contains("12")) {
                    PV += (float) (Float.valueOf(info.getPrice()) * info.getCount() * discount);
                    allPrice += (float) (Float.valueOf(info.getPrice()) * info.getCount());
                    RealPay += (float) (Float.valueOf(info.getPrice()) * info.getCount() * discount);
                } else if (info.getPtid().contains("12")) {
                    SaleAids = Float.valueOf(info.getPrice()) * info.getCount();
                    allPrice += SaleAids;
                    RealPay += SaleAids;
                }
                if (info.getCount() != 0) {
                    stringBuffer.append(info.getId() + ",");
                    sbCount.append(info.getCount() + ",");
                }
            }
            if (sbCount.length() != 0) {
                ids = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                count = sbCount.toString().substring(0, sbCount.toString().length() - 1);
            }
            if (!info.flag)
                flag = false;
        }
        DecimalFormat df = new DecimalFormat("0.00");
        mAllPrice.setText(String.format("%.2f", allPrice) + "");
        mSecond_num.setText("共 " + list.size() + " 种商品");
        mConfirmPayment.setText("确认结算（" + String.format("%.2f", RealPay) + ")");
        if (!"0".equals(SPUtils.get(getApplicationContext(), "secondAct", "").toString())) {
            activeProInfosAdapter = new ArrayList<ActiveProInfo>();
            if (activeInfos.size() == 1) {
                mGiftText.setVisibility(View.VISIBLE);
                //固定数值
                if ("方案一".equals(activeInfos.get(0).getAction())) {
                    //不累计
                    if (RealPay >= activeInfos.get(0).getOrderpayment()) {
                        activeFlag = 1;
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(0).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(0).getPrice());
                            }
                        }
                    }
                } else if ("方案二".equals(activeInfos.get(0).getAction())) {
                    //累计
                    int giftCount = (int) (RealPay / activeInfos.get(0).getOrderpayment());
                    if (giftCount < 1) {
                        mGiftText.setVisibility(View.GONE);
                    } else {
                        activeFlag = giftCount;
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(0).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(0).getPrice() * activeFlag);
                            }
                        }
                    }
                }
            } else if (activeInfos.size() == 2) {
                mGiftText.setVisibility(View.VISIBLE);
                //区间
                if ("方案一".equals(activeInfos.get(0).getAction())) {
                    activeFlag = 1;
                    if (RealPay >= activeInfos.get(0).getOrderpayment()) {
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(0).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(0).getPrice());
                            }
                        }
                    } else if (RealPay >= activeInfos.get(1).getOrderpayment()) {
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(1).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(1).getPrice());
                            }
                        }
                    } else {
                        mGiftText.setVisibility(View.GONE);
                    }
                }
            } else if (activeInfos.size() == 3) {
                mGiftText.setVisibility(View.VISIBLE);
                //区间
                if ("方案一".equals(activeInfos.get(0).getAction())) {
                    activeFlag = 1;
                    if (RealPay >= activeInfos.get(0).getOrderpayment()) {
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(0).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(0).getPrice());
                            }
                        }
                    } else if (RealPay >= activeInfos.get(1).getOrderpayment()) {
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(1).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(1).getPrice());
                            }
                        }
                    } else if (RealPay >= activeInfos.get(2).getOrderpayment()) {
                        for (int i = 0; i < activeProInfos.size(); i++) {
                            if (activeInfos.get(2).getId().equals(activeProInfos.get(i).getActiveid())) {
                                //创建赠品适配器
                                activeProInfosAdapter.add(activeProInfos.get(i));
                                mGiftText.setText("赠品：价值 ￥" + activeInfos.get(2).getPrice());
                            }
                        }
                    } else {
                        mGiftText.setVisibility(View.GONE);
                    }
                }
            }
            if (activeProInfosAdapter != null) {
                giftAdapter = new GiftAdapter(activeProInfosAdapter, ConfirmPayActivity.this, activeFlag);
                mGiftlv.setAdapter(giftAdapter);
                if (activeProInfosAdapter.size() == 0) {
                    mGiftText.setVisibility(View.GONE);
                }
            } else {
                mGiftText.setVisibility(View.GONE);
            }
        } else {
            mGiftText.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirmpay_back:
                finish();
                break;
            case R.id.confirmPay_changeAddress:
                Intent intent2choiceaddress = new Intent(this, AddressChoiceActivity.class);
                startActivityForResult(intent2choiceaddress, REQUSET);
                break;
            case R.id.confirmpayment:
                if (mAddress.getText().toString().contains("没有")) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    attemptCreateOrder("1");
                }

                break;
            case R.id.confirmAddcart:
                if (mAddress.getText().toString().contains("没有")) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    attemptCreateOrder("2");
                }

                break;
        }
    }

    private void attemptCreateOrder(String flag) {

        if (allPrice == 0.0) {
            Toast.makeText(this, "请选择购买物品的数量,谢谢", Toast.LENGTH_SHORT).show();
            return;
        } else if (RealPay <= 2000.0) {
            Toast.makeText(this, "二次进货的实付金额不能小于2000", Toast.LENGTH_SHORT).show();
            return;
        } else if (mAddress.getText().toString().contains("没有")) {
            Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
            return;
        }
        MD5 md = new MD5();
        String md5Realpayment = md.toMD5(String.valueOf(RealPay));
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.order.createorder");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("ids", ids);       //产品id
        form.put("allPrice", count); //件数
        form.put("adressid", addressid); //地址
        form.put("customerid", customerId); //客户id
        form.put("orderType", "3");
        form.put("orderClass", "3");
        form.put("orderPrice", String.valueOf(allPrice)); //总价
        form.put("orderRealpayment", String.valueOf(RealPay)); //实付价
        form.put("orderAllpv", String.valueOf(PV)); //pv
        form.put("orderRealpv", String.valueOf(PV)); //pv
        form.put("md5Realpayment", md5Realpayment);//加密
        form.put("flag", mDeptFlag);
        form.put("orderName", "A");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> ConfirmPayActivity.this.showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();
                    if (!"".equals(result)) {
                        if ("0".equals(result)) {
                            Toast.makeText(ConfirmPayActivity.this, "确认结算失败，请重新提交", Toast.LENGTH_SHORT).show();
                        } else {
                            mConfirmPayment.setEnabled(true);
                            if ("1".equals(flag)) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmPayActivity.this);
                                builder.setMessage("订单已提交到销售管理页面！\n点击“确定”继续支付，\n点击“取消”返回继续购买");
                                builder.setTitle("提示");
                                builder.setPositiveButton("确定", (dialog1, which) -> {
                                    dialog1.dismiss();
                                    //设置你的操作事项
                                    Intent intent2PayPwd = new Intent(ConfirmPayActivity.this, ConfirmPayPwdActivity.class);
                                    intent2PayPwd.putExtra("orderId", result);
                                    startActivity(intent2PayPwd);
                                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "二次进货，创建订单,订单编号：" + result + ",价格：" + RealPay + ",赠品" + mGiftText.getText());
                                    finish();
                                });

                                builder.setNegativeButton("取消",
                                        (dialog12, which) -> {
                                            dialog12.dismiss();
                                            finish();
                                        });
                                builder.create().show();
                            } else if ("2".equals(flag)) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmPayActivity.this);
                                builder.setMessage("订单已提交到销售管理页面！\n请返回查看");
                                builder.setTitle("提示");
                                builder.setPositiveButton("确定", (dialog13, which) -> {
                                    MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                                            SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "二次进货，添加购物车,订单编号：" + result + ",价格：" + RealPay + ",赠品" + mGiftText.getText());
                                    dialog13.dismiss();
                                    finish();
                                });
                                builder.create().show();
                            }
                            mConfirmPayment.setEnabled(true);
                        }
                    }

                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });


    }

    //获取默认地址
    public void attemptAddress() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerId", customerId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    Log.e("result", result);
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(ConfirmPayActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
//                            Toast.makeText(ConfirmPayActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                            mAddress.setText("您还没有收货地址，请到个人设置中设置");
                        } else {
                            listAddress = JSON.parseArray(result, AddressInfo.class);
                            for (int i = 0; i < listAddress.size(); i++) {
                                if ("1".equals(listAddress.get(i).getAddress_default())) {
                                    addressid = listAddress.get(i).getId();
                                    mUsername.setText("收货人：" + listAddress.get(i).getReceivername());
                                    mPhone.setText(listAddress.get(i).getPhone());
                                    mAddress.setText("地址：" + listAddress.get(i).getCountryname() + listAddress.get(i).getProvincename()
                                            + listAddress.get(i).getCityname() + listAddress.get(i).getAreaname() + listAddress.get(i).getStreet());
                                }
                            }
                        }
                    } else {
                        //在获取不到数据时的处理
                        mAddress.setText("您还没有默认地址，请到个人设置中添加");
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销观察者
        adapter.unregisterDataSetObserver(sumObserver);
    }
}
